package org.adorsys.aderp.aderplogin.client;

import org.adorsys.aderp.aderplogin.domain.AderpUser;
import org.adorsys.aderp.aderplogin.service.AderpUserService;
import org.adorsys.aderp.jpa.security.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class UserDetailServiceClient implements UserDetailsService {

	@Autowired
	private AderpUserService aderpUserService;
	
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {

		if (StringUtils.isBlank(username)) {
			throw new UsernameNotFoundException(
					"Estate user with email not found");
		}
		
		AderpUser user = aderpUserService.findByUserName(username);
		if (user == null)
			throw new UsernameNotFoundException(
					"User with email not found");
		
		return UserDetailsHelper.createUserDetails(user);
	}

	public AderpUser getAderpUser() {
		UserDetails userDetails = SecurityUtils.getUserDetails();
		if (userDetails == null)
			return null;
		String username = userDetails.getUsername();
		return aderpUserService.findByUserName(username);
	}
}
